package com.renwei.yunlong.fragment;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.CommonSearchActivity;
import com.renwei.yunlong.activity.contacts.AddEmployeeActivity;
import com.renwei.yunlong.activity.contacts.ContactDynamicActivity;
import com.renwei.yunlong.activity.contacts.SeeContactsByDepartmentActivity;
import com.renwei.yunlong.activity.contacts.SeeContactsByEnterpriseActivity;
import com.renwei.yunlong.activity.contacts.SeeContactsByFuctionActivity;
import com.renwei.yunlong.activity.me.DisplayUserInfoActivity;
import com.renwei.yunlong.adapter.SortContactAdapter;
import com.renwei.yunlong.base.BaseLazyFragment;
import com.renwei.yunlong.bean.EmpInfoJsonBean;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.bean.contacts.ContactsBean;
import com.renwei.yunlong.event.ContactsRefreshEvent;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.ContactPingyinComparator;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.PinyinUtils;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.SearchImage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * 通讯录--fragment
 * <p>
 * Created by Administrator on 2017/8/24.
 */

public class ContactsFragment extends BaseLazyFragment implements View.OnClickListener, HttpTaskListener, AdapterView.OnItemClickListener {

    private static final int from_type = 0;
    private View HeaderView;
    private ListView sortListView;
    private SortContactAdapter contactAdapter;
    private List<Contact> contactList;
    //根据拼音来排列ListView里面的数据类
    private ContactPingyinComparator contactPingyinComparator;
    private int page = 1;
    private SearchImage mSearchImage;
    private SmartRefreshLayout refreshLayout;


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(ContactsRefreshEvent event) {
        requestAllContactInfo();
    }

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.fragment_contacts;
    }

    @Override
    public void onLazyLoad() {
        View view  = getView();
        mSearchImage = view.findViewById(R.id.search_image);
        mSearchImage.setOnClickListener(this);
        HeaderView = LayoutInflater.from(getActivity()).inflate(R.layout.contact_head, null);
        view.findViewById(R.id.iv_back).setVisibility(View.GONE);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        ImageView ivCont = view.findViewById(R.id.iv_cont);//通讯录
        ImageView ivEdit = view.findViewById(R.id.iv_edit);//通讯录
        RelativeLayout rlDepartment = HeaderView.findViewById(R.id.rl_department);
        RelativeLayout rlFunction = HeaderView.findViewById(R.id.rl_function);
        RelativeLayout rlFriends = HeaderView.findViewById(R.id.rl_friends);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        // 实例化汉字转拼音类
        contactPingyinComparator = new ContactPingyinComparator();
        sortListView = view.findViewById(R.id.country_lvcountry);
        sortListView.addHeaderView(HeaderView);
        contactAdapter = new SortContactAdapter(getContext(), from_type, companyType, contactList);
        sortListView.setAdapter(contactAdapter);
        contactList = new ArrayList<>();
        // 根据输入框输入值的改变来过滤搜索
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                requestAllContactInfo();
            }
        });
        tvTitle.setText("通讯录");
        ivCont.setVisibility(View.VISIBLE);
        ivCont.setOnClickListener(this);
        ivEdit.setVisibility(View.VISIBLE);
        ivEdit.setOnClickListener(this);
        rlDepartment.setOnClickListener(this);
        rlFunction.setOnClickListener(this);
        rlFriends.setOnClickListener(this);
        sortListView.setOnItemClickListener(this);
        if ("1".equals(companyType)) {
            if (ownerBean.getRows() != null && ownerBean.getRows().getEmployee()
                    != null && ownerBean.getRows().getEmployee().getRoleId()
                    != null && "12".equals(ownerBean.getRows().getEmployee().getRoleId()) || "10".equals(ownerBean.getRows().getEmployee().getRoleId())) {
                ivEdit.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams ivAddParams = (RelativeLayout.LayoutParams) ivEdit.getLayoutParams();
                ivAddParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                ivEdit.setLayoutParams(ivAddParams);
                RelativeLayout.LayoutParams ivContParams = (RelativeLayout.LayoutParams) ivCont.getLayoutParams();
                ivContParams.addRule(RelativeLayout.LEFT_OF, R.id.iv_edit);
                ivCont.setLayoutParams(ivContParams);
            } else {
                ivEdit.setVisibility(View.GONE);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivCont.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                ivCont.setLayoutParams(params);
            }
        } else {
            if (serviceLoginBean.getRows() != null && serviceLoginBean.getRows().getEmployee()
                    != null && serviceLoginBean.getRows().getEmployee().getRoleId()
                    != null && "12".equals(serviceLoginBean.getRows().getEmployee().getRoleId()) || "10".equals(serviceLoginBean.getRows().getEmployee().getRoleId())) {
                ivEdit.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams ivAddParams = (RelativeLayout.LayoutParams) ivEdit.getLayoutParams();
                ivAddParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                ivEdit.setLayoutParams(ivAddParams);
                RelativeLayout.LayoutParams ivContParams = (RelativeLayout.LayoutParams) ivCont.getLayoutParams();
                ivContParams.addRule(RelativeLayout.LEFT_OF, R.id.iv_edit);
                ivCont.setLayoutParams(ivContParams);
            } else {
                ivEdit.setVisibility(View.GONE);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ivCont.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                ivCont.setLayoutParams(params);
            }
        }


        requestAllContactInfo();
    }

    private void requestAllContactInfo() {
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        String json = "";
        if ("1".equals(companyType)) {
            json = new Gson().toJson(new EmpInfoJsonBean(ownerBean.getRows().getEmployeeId(), "", page, 100));
        } else if ("2".equals(companyType)) {
            json = new Gson().toJson(new EmpInfoJsonBean(serviceLoginBean.getRows().getEmployeeId(), "", page, 100));
        }
        manager.queryContactByCharacter(getActivity(), json, this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.e("全部联系人" + result);
        switch (requestId) {
            case 1:
                ContactsBean bean = new Gson().fromJson(result, ContactsBean.class);
                int code = bean.getMessage().getCode();
                if (code == 200) {
                    contactList = filledPingYing(bean.getRows());
                    // 根据a-z进行排序源数据
                    Collections.sort(contactList, contactPingyinComparator);
                    contactAdapter.refresh(contactList);
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                refreshLayout.finishRefresh();
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        refreshLayout.finishRefresh();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_department://部门
                startActivity(new Intent(getActivity(), SeeContactsByDepartmentActivity.class));
                break;
            case R.id.rl_function://职能
                startActivity(new Intent(getActivity(), SeeContactsByFuctionActivity.class));
                break;
            case R.id.rl_friends://好友
                startActivity(new Intent(getActivity(), SeeContactsByEnterpriseActivity.class));
                break;
            case R.id.iv_edit://
                AddEmployeeActivity.openActivity(getActivity());
                break;
            case R.id.iv_cont: // 联勤动态
                ContactDynamicActivity.OpenActivity(getContext());
                break;
            case R.id.search_image:
                CommonSearchActivity.OpenActivityFromContact(getActivity(), v, ContactsFragment.class, 999, from_type, companyType);
                break;
            default:
                break;

        }

    }


    /**
     * 为列表填充数据
     *
     * @param contactList
     * @return
     */
    //转拼音
    private List<Contact> filledPingYing(List<Contact> contactList) {
        for (int i = 0; i < contactList.size(); i++) {
            Contact appEmployee = contactList.get(i);
            if (appEmployee != null) {
                String name = appEmployee.getName();
                //汉字转换成拼音
                String pinyin = PinyinUtils.getPingYin(name);
                String sortString = pinyin.substring(0, 1).toUpperCase();
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    appEmployee.setLetter(sortString.toUpperCase());
                } else {
                    appEmployee.setLetter("#");
                }
            }

        }
        return contactList;
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        if (contactAdapter != null) {
            DisplayUserInfoActivity.OpenActivity(getContext(), contactList.get(position).getEmployeeId(), "");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }


}
